package com.zbkj.service.service.impl.splittingAccount;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbkj.common.constants.OrderConstants;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.product.Product;
import com.zbkj.common.model.shop.*;
import com.zbkj.common.model.splittingAccount.EbSplitAccount;
import com.zbkj.service.dao.shop.EbOrderAdvertisingCostDao;
import com.zbkj.service.service.*;
import com.zbkj.service.service.splittingAccount.SplittingAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 分账业务实现类
 */
@Service
@Slf4j
public class OrderSplitAccountImpl implements OrderSplittingAccountService {
    @Autowired
    SplittingAccountService splittingAccountService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    AdOrderAdvertisingService adOrderAdvertisingService;
    @Autowired
    ProductService productService;
    @Autowired
    BusinessApplyService businessApplyService;
    @Autowired
    AdAgentApplicationService adAgentApplicationService;
    @Autowired
    BagSpecsService bagSpecsService;
    @Autowired
    DevelopAdApplyService developAdApplyService;
    @Autowired
    EbOrderAdvertisingCostDao ebOrderAdvertisingCostDao;
    @Autowired
    MerchantService merchantService;

    /**
     * 提交分账信息
     *
     * @param order 订单信息
     */
    public void addSplittingAccount(Order order) {
        List<OrderDetail> orderDetailList = orderDetailService.getByOrderNo(order.getOrderNo());
        for (OrderDetail orderDetail : orderDetailList) {
            //计算每个商品的分账信息
            if (order.getType().equals(OrderConstants.GROUP_BUYING_GOODS_TYPE)) {
                //如果是团购订单
                //查询是否存在团购广告

            } else if (order.getType().equals(OrderConstants.ORDER_TYPE_NORMAL)) {
                //一件代发订单
                //目前仅有一件代发订单有分账
                try {
                    EbSplitAccount ebSplitAccount = addProduct(order, orderDetail);
                    if (ebSplitAccount != null) {
                        log.info("ebSplitAccount:{}", ebSplitAccount.toString());
                    } else {
                        log.info("ebSplitAccount is null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("分账异常:orderNo{},type:{}", order.getOrderNo(), order.getType());
                    log.error("分账异常订单明细:{}", orderDetail.toString());
                }

            }
        }

    }

    /**
     * 批量获取分账信息
     *
     * @param orderNo
     * @return
     */
    @Override
    public List<EbSplitAccount> getSplitAccountOrderSn(String orderNo) {
        return splittingAccountService.getSplitAccount(orderNo);
    }

    @Override
    public void setEbSplitAccount(EbSplitAccount ebSplitAccount) {
        splittingAccountService.setEbSplitAccount(ebSplitAccount);
    }

    //创建团购订单分账信息
    private EbSplitAccount addProduct(Order order, OrderDetail orderDetail) {
        //查询一键代发商品信息
        Product product = productService.getById(orderDetail.getProductId());
        //团购merType=4 一件代发=1,3
        //超过该订单 30 天期限后，该产品销售利润全归公司； 仅查30天内订单
        int day = 30;
        OrderAdvertising orderAdvertising = adOrderAdvertisingService
                .getSplitOrderAdvertising(orderDetail.getProductId(), day, 1, 3);
        if (orderAdvertising == null) {
            log.info("orderAdvertising is null");
            return null;
        }

        // 商家申请信息
        BusinessApply businessApply = businessApplyService.getMerType(orderAdvertising.getUserId(), orderAdvertising.getMerType());
        if (businessApply == null) {
            log.info("businessApply is null");
            return null;
        }
        //选品人
        DevelopAdApply developAdApply = developAdApplyService.get(businessApply.getInvitationCode());
        if (developAdApply == null) {
            log.info("developAdApply is null");
            return null;
        }
        //市代理
        AdAgentApplication adAgentApplication = adAgentApplicationService.get(developAdApply.getInvitationCode());

        //查询到有开卖的产品,开始计算分账金额
        /// 计算毛利 productPrice-supplyPrice
        //计算订单获利
        //产品成本
        BigDecimal supplyPrice = product.getSupplyPrice().multiply(new BigDecimal(orderDetail.getPayNum()));
        //销售收入
        BigDecimal productPrice = orderDetail.getPrice().multiply(new BigDecimal(orderDetail.getPayNum()));
        //lattice 格子数
        Integer lattice = orderAdvertising.getLattice();
        //flow_number 总流量数
        Integer flowNumber = orderAdvertising.getFlowNumber();
        //bagSpecsId 查询 BagSpecs cost袋子成本价
        BagSpecs bagSpecs = bagSpecsService.get(orderAdvertising.getBagSpecsId());
        // 袋子成本价
        BigDecimal cost = bagSpecs.getCost();
        /// 计算行销费 flow_number*bagSpecsId*latticed
        BigDecimal marketingExpenses = cost.multiply(new BigDecimal(flowNumber).multiply(new BigDecimal(lattice)));
        //理论毛利
        BigDecimal profit = productPrice.subtract(supplyPrice);
        log.info("成本：{} 销售价：{},毛利:{}", supplyPrice, productPrice, profit);
        if (profit.compareTo(new BigDecimal(0)) <= 0) {
            log.info("无利润");
            return null;
        }
        EbOrderAdvertisingCost ebOrderAdvertisingCost = ebOrderAdvertisingCostDao.selectOne(new QueryWrapper<EbOrderAdvertisingCost>()
                .lambda()
                .eq(EbOrderAdvertisingCost::getOrderAdvertisingNumber, orderAdvertising.getOrderSn())
                .last("limit 1")
        );
        //剩余分配金额
        BigDecimal remainingAmount = new BigDecimal(0);
        if (ebOrderAdvertisingCost == null) {
            //统计是否公司已收完行销费
            ebOrderAdvertisingCost = new EbOrderAdvertisingCost();
            ebOrderAdvertisingCost.setOrderAdvertisingNumber(orderAdvertising.getOrderSn());
            ebOrderAdvertisingCost.setEstimatedCost(marketingExpenses);
            ebOrderAdvertisingCost.setReceivedAmount(profit);
            ebOrderAdvertisingCost.setStatus(0);
            ebOrderAdvertisingCostDao.insert(ebOrderAdvertisingCost);
            return null;
        } else {
            if (ebOrderAdvertisingCost.getStatus() == 0) {
                /**
                 * 应收成本
                 */
                BigDecimal estimatedCost = ebOrderAdvertisingCost.getEstimatedCost();
                /**
                 * 实收成本
                 */
                BigDecimal receivedAmount = ebOrderAdvertisingCost.getReceivedAmount();
                if (estimatedCost.compareTo(receivedAmount.add(profit)) > 0) {
                    //公司未完成应收成本
                    ebOrderAdvertisingCost.setReceivedAmount(receivedAmount.add(profit));

                    ebOrderAdvertisingCostDao.updateById(ebOrderAdvertisingCost);
                    log.info("应收成本累加:{}", ebOrderAdvertisingCost.toString());
                } else {
                    if (estimatedCost.compareTo(ebOrderAdvertisingCost.getReceivedAmount()) == 0) {
                        //完成应收
                        ebOrderAdvertisingCost.setStatus(1);
                        ebOrderAdvertisingCost.setReceivedAmount(receivedAmount.add(profit));
                    } else {
                        //有剩余 需分配
                        BigDecimal totalReceivedAmount = receivedAmount.add(profit);
                        //剩余部分利润可分配
                        remainingAmount = totalReceivedAmount.subtract(ebOrderAdvertisingCost.getEstimatedCost());
                        ebOrderAdvertisingCost.setReceivedAmount(ebOrderAdvertisingCost.getEstimatedCost());
                    }
                    ebOrderAdvertisingCostDao.updateById(ebOrderAdvertisingCost);
                    log.info("完成应收:{}", ebOrderAdvertisingCost.toString());
                }
            } else {
                //剩余全利润可分配
                remainingAmount = profit;
            }
            log.info("剩余全利润可分配:{}", remainingAmount);
            // 大于1毛钱,开始分配
            if (remainingAmount.compareTo(BigDecimal.ZERO) >= 0) {
                // 将金额转换为分（乘以100）进行整数运算，避免精度丢失
                long totalCents = remainingAmount.multiply(BigDecimal.valueOf(100)).longValue();

                // 计算各角色分账金额（以分为单位）
                // 公司保留75%
                long companyCents = Math.round(totalCents * 0.75);

                // 选品人15%
                long selectorCents = Math.round(totalCents * 0.15);

                // 市代理7%
                long cityAgentCents = Math.round(totalCents * 0.07);

                // 渠道3%
                long channelCents = Math.round(totalCents * 0.03);

                // 检查最小分配金额（最低1分钱，总和低于3分钱不分配）
                if ((selectorCents + cityAgentCents + channelCents) < 3) {
                    // 如果其他角色分配总额低于3分钱，则不分配给这些角色
                    companyCents = totalCents; // 全部分配给公司
                    selectorCents = 0;
                    cityAgentCents = 0;
                    channelCents = 0;
                } else {
                    // 确保每个角色至少获得1分钱（如果分配比例大于0）
                    if (selectorCents > 0 && selectorCents < 1) {
                        selectorCents = 1;
                    }

                    if (cityAgentCents > 0 && cityAgentCents < 1) {
                        cityAgentCents = 1;
                    }

                    if (channelCents > 0 && channelCents < 1) {
                        channelCents = 1;
                    }
                }

                // 转换回元为单位（除以100）
                // 公司保留75%
                BigDecimal companyAmount = new BigDecimal(companyCents).divide(BigDecimal.valueOf(100));
                // 选品人15%
                BigDecimal selectorAmount = new BigDecimal(selectorCents).divide(BigDecimal.valueOf(100));
                // 市代理7%
                BigDecimal cityAgentAmount = new BigDecimal(cityAgentCents).divide(BigDecimal.valueOf(100));
                // 渠道3%
                BigDecimal channelAmount = new BigDecimal(channelCents).divide(BigDecimal.valueOf(100));

                // 处理除不尽的余数部分，将余数加到公司份额中
                BigDecimal totalAllocated = companyAmount.add(selectorAmount)
                        .add(cityAgentAmount)
                        .add(channelAmount);
                BigDecimal remainder = remainingAmount.subtract(totalAllocated);
                //公司分配利润
                companyAmount = companyAmount.add(remainder);
                //渠道费暂时留给公司
                companyAmount = companyAmount.add(channelAmount);
                EbSplitAccount ebSplitAccount = new EbSplitAccount();
                ebSplitAccount.setMerId(String.valueOf(order.getMerId()));
                ebSplitAccount.setOrderNo(order.getOrderNo());
                ebSplitAccount.setOrderAmount(productPrice);
                ebSplitAccount.setOrderType("1");
                ebSplitAccount.setOrderDate(orderDetail.getCreateTime());
                ebSplitAccount.setProductId(String.valueOf(orderDetail.getProductId()));
                ebSplitAccount.setProductName(orderDetail.getProductName());
                ebSplitAccount.setRelatedOrder(orderAdvertising.getOrderSn());
                ebSplitAccount.setGrossProfit(profit);
                ebSplitAccount.setMarketingFee(remainingAmount);
                ebSplitAccount.setSalesRevenue(productPrice);
                ebSplitAccount.setProductCost(supplyPrice);
                ebSplitAccount.setAdPositionFee(cost);
                ebSplitAccount.setTotalQuantity(new BigDecimal(flowNumber));
                ebSplitAccount.setUnitPrice(cost);
                ebSplitAccount.setMerchandiserMerId(String.valueOf(developAdApply.getUserId()));
                ebSplitAccount.setMerchandiserName(developAdApply.getName());
                ebSplitAccount.setMerchandiserAmount(selectorAmount);
                Merchant merchant = merchantService.getById(orderDetail.getMerId());
                if (merchant != null) {

                    ebSplitAccount.setMerName(orderDetail.getMerName());
                }
                if (adAgentApplication != null) {
                    ebSplitAccount.setAgentMerId(String.valueOf(adAgentApplication.getUserId()));
                    ebSplitAccount.setAgentName(adAgentApplication.getAccountName());
                }
                ebSplitAccount.setAgentAmount(cityAgentAmount);
                ebSplitAccount.setCompany("网慧公司");
                //暂时无渠道分配
//                ebSplitAccount.setChannelId();
//                ebSplitAccount.setChannelName()
//                ebSplitAccount.setChannelAmount()
                ebSplitAccount.setCompanyAmount(companyAmount);
                ebSplitAccount.setStatus(false);
                return splittingAccountService.addSplitAccount(ebSplitAccount);
            } else {
                EbSplitAccount ebSplitAccount = new EbSplitAccount();
                ebSplitAccount.setMerId(String.valueOf(order.getMerId()));
                ebSplitAccount.setOrderNo(order.getOrderNo());
                ebSplitAccount.setOrderAmount(productPrice);
                ebSplitAccount.setOrderType("1");
                ebSplitAccount.setOrderDate(orderDetail.getCreateTime());
                ebSplitAccount.setProductId(String.valueOf(orderDetail.getProductId()));
                ebSplitAccount.setProductName(orderDetail.getProductName());
                ebSplitAccount.setRelatedOrder(orderAdvertising.getOrderSn());
                ebSplitAccount.setGrossProfit(profit);
                ebSplitAccount.setMarketingFee(remainingAmount);
                ebSplitAccount.setSalesRevenue(productPrice);
                ebSplitAccount.setProductCost(supplyPrice);
                ebSplitAccount.setAdPositionFee(cost);
                ebSplitAccount.setTotalQuantity(new BigDecimal(flowNumber));
                ebSplitAccount.setUnitPrice(cost);
                ebSplitAccount.setMerchandiserMerId(String.valueOf(developAdApply.getUserId()));
                ebSplitAccount.setMerchandiserName(developAdApply.getName());
                ebSplitAccount.setMerchandiserAmount(BigDecimal.ZERO);
                ebSplitAccount.setAgentMerId(String.valueOf(adAgentApplication.getUserId()));
                ebSplitAccount.setAgentName(adAgentApplication.getAccountName());
                ebSplitAccount.setAgentAmount(BigDecimal.ZERO);
                ebSplitAccount.setCompany("网慧公司");
                Merchant merchant = merchantService.getById(orderDetail.getMerId());
                if (merchant != null) {

                    ebSplitAccount.setMerName(orderDetail.getMerName());
                }
                //暂时无渠道分配
//                ebSplitAccount.setChannelId();
//                ebSplitAccount.setChannelName()
//                ebSplitAccount.setChannelAmount()
                ebSplitAccount.setCompanyAmount(remainingAmount);
                ebSplitAccount.setStatus(false);
                return splittingAccountService.addSplitAccount(ebSplitAccount);
            }

        }
    }

}
